<template>
  <view class="service-detail">
    
    <!-- 服务图片 -->
    <!-- 加载状态提示 -->
    <view v-if="loadingServiceDetail" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 无数据提示 -->
    <view v-else-if="!currentService.id" class="empty-container">
      <text class="empty-text">暂无服务数据</text>
    </view>

    <swiper 
      v-else
      class="service-detail__swiper" 
      :indicator-dots="true" 
      :autoplay="true"
      :interval="3000"
      :duration="500"
      indicator-active-color="#07c160"
      indicator-color="rgba(255, 255, 255, 0.5)"
      circular
    >
      <swiper-item v-for="(image, index) in serviceDetail.images" :key="index" class="swiper-item">
        <image :src="image" mode="aspectFill" class="service-detail__image" />
      </swiper-item>
    </swiper>
    
    <!-- 图片下面的圆角遮罩 -->
    <view class="curve-mask"></view>
    
    <!-- 服务标题价格区 -->
    <view class="service-detail__header">
      <view class="service-detail__title-area">
        <view class="service-detail__title">{{ serviceDetail.name }}</view>
        <view class="service-detail__tag" v-if="serviceDetail.tag">
          <text>{{ serviceDetail.tag }}</text>
        </view>
      </view>
      
      <view class="service-detail__price-area">
        <view class="service-detail__price-box">
          <text class="service-detail__price-symbol">¥</text>
          <text class="service-detail__price">{{ serviceDetail.price }}</text>
          <text class="service-detail__original-price" v-if="serviceDetail.originalPrice">¥{{ serviceDetail.originalPrice }}</text>
        </view>
        <view class="service-detail__discount" v-if="serviceDetail.discount">
          <text>{{ serviceDetail.discount }}</text>
        </view>
      </view>
      
      <view class="service-detail__stats">
        <view class="service-detail__stat-item">
          <text class="service-detail__stat-value">{{ serviceDetail.sales }}</text>
          <text class="service-detail__stat-label">已售出</text>
        </view>
        <view class="service-detail__stat-divider"></view>
        <view class="service-detail__stat-item">
          <text class="service-detail__stat-value">{{ serviceDetail.rating }}%</text>
          <text class="service-detail__stat-label">好评率</text>
        </view>
      </view>
    </view>
    
    <!-- 订单选项区 -->
    <view class="service-detail__options-panel">
      <!-- 服务规格选择 -->
      <view class="service-detail__option-item" @click="showOptionsPopup">
        <view class="service-detail__option-left">
          <text class="service-detail__option-label">规格</text>
          <text class="service-detail__option-value" :class="{'service-detail__option-placeholder': !selectedOption}">
            {{ selectedOption ? selectedOption.name : '请选择' }}
          </text>
        </view>
        <view class="service-detail__option-right">
          <view class="service-detail__option-icon">
            <text class="service-detail__option-arrow">›</text>
          </view>
        </view>
      </view>
      
      <!-- 服务时间选择 -->
      <view class="service-detail__option-item" @click="showTimePopup">
        <view class="service-detail__option-left">
          <text class="service-detail__option-label">时间</text>
          <text class="service-detail__option-value" :class="{'service-detail__option-placeholder': !selectedTime}">
            {{ selectedTime ? selectedTime : '请选择' }}
          </text>
        </view>
        <view class="service-detail__option-right">
          <view class="service-detail__option-icon">
            <text class="service-detail__option-arrow">›</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 服务介绍面板 -->
    <view class="service-section">
      <view class="service-section-title">
        <text class="service-section-title-text">服务介绍</text>
      </view>
      <view class="service-description">
        <text>{{ serviceDetail.description }}</text>
      </view>
    </view>
    
    <!-- 服务须知 -->
    <view class="service-section">
      <view class="service-section-title">
        <text class="service-section-title-text">服务须知</text>
      </view>
      <view class="service-notice">
        <view class="notice-item" v-for="(item, index) in serviceDetail.notices" :key="index">
          <text class="notice-icon">•</text>
          <text class="notice-text">{{ item }}</text>
        </view>
      </view>
    </view>
    
    <!-- 用户评价面板 -->
    <view class="service-section review-section">
      <view class="service-section-title review-header">
        <text class="service-section-title-text">用户评价</text>
        <view class="review-action" @click="goToReviews">
          <text class="review-action-text">查看全部</text>
          <text class="review-action-icon">›</text>
        </view>
      </view>
      <service-reviews 
        :reviews="serviceDetail.reviews" 
        :limit="2" 
        :show-view-all="false"
        @view-all="goToReviews"
      />
    </view>
    
    <!-- 底部操作栏 -->
    <service-footer 
      :disabled="!selectedOption || !selectedTime" 
      button-text="立即预约" 
      @action-click="handleFooterAction" 
      @button-click="buyNow"
    />
    
    <!-- 服务规格选择弹窗 -->
    <custom-popup 
      :show="showOptions" 
      title="选择服务规格" 
      @close="closeOptionsPopup"
      @confirm="confirmOption"
    >
      <service-options 
        :options="serviceDetail.options" 
        :selected-index="selectedOptionIndex"
        @select="selectOption"
      />
    </custom-popup>
    
    <!-- 服务时间选择弹窗 -->
    <custom-popup 
      :show="showTime" 
      title="选择服务时间" 
      @close="closeTimePopup"
      @confirm="confirmTime"
    >
      <picker-view
        class="time-picker"
        :value="timePickerValue"
        @change="onTimePickerChange"
      >
        <picker-view-column>
          <view class="picker-item" v-for="(date, index) in dateArray" :key="index">{{ date }}</view>
        </picker-view-column>
        <picker-view-column>
          <view class="picker-item" v-for="(time, index) in timeArray" :key="index">{{ time }}</view>
        </picker-view-column>
      </picker-view>
    </custom-popup>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue';
import { useStore } from 'vuex';

// 引入组件
import ServicePanel from '@/components/service/ServicePanel.vue';
import ServiceReviews from '@/components/service/ServiceReviews.vue';
import ServiceOptions from '@/components/service/ServiceOptions.vue';
import ServiceFooter from '@/components/service/ServiceFooter.vue';
import CustomPopup from '@/components/service/CustomPopup.vue';

// 初始化store
const store = useStore();

// 从Vuex获取服务详情
const serviceId = ref(0);
const currentService = computed(() => store.state.service.currentService || {});
const loadingServiceDetail = computed(() => store.state.service.loadingServiceDetail);

// 服务详情数据 (兼容处理，基于Vuex里的数据)
const serviceDetail = computed(() => {
  const service = currentService.value;
  console.log('当前服务数据：', service);
  if (!service || !service.id) {
    return {
      id: 0,
      name: '加载中...',
      price: 0,
      images: [],
      description: '',
      notices: [],
      options: [],
      reviews: []
    };
  }
  
  return {
    id: service.id,
    name: service.name,
    price: `¥${service.price}${service.unit ? '/' + service.unit : ''}`,
    originalPrice: service.originalPrice,
    sales: service.orderCount || 0,
    rating: Math.round((service.rating || 0) * 20), // 转换为百分比
    images: service.images && service.images.length > 0 ? service.images : [
      'https://picsum.photos/seed/service1/800/600',
      'https://picsum.photos/seed/service2/800/600'
    ],
    description: service.description || '暂无描述',
    notices: [
      '服务高峰期请提前预约',
      '大件、超重物品需额外付费',
      '恶劣天气可能会影响配送时间'
    ],
    options: service.options && service.options.length > 0 ? service.options : [
      { id: 1, name: '基础服务', price: service.price, description: '标准服务内容' }
    ],
    reviews: store.state.service.reviews.slice(0, 2) // 只取前两条评价
  };
});

// 弹窗控制状态
const showOptions = ref(false);
const showTime = ref(false);

// 选中的选项
const selectedOptionIndex = ref(-1);
const selectedOption = computed(() => {
  if (selectedOptionIndex.value >= 0 && serviceDetail.value.options) {
    return serviceDetail.value.options[selectedOptionIndex.value];
  }
  return null;
});

// 时间选择相关
const dateArray = [
  '今天',
  '明天',
  '后天'
];

const timeArray = [
  '9:00-10:00',
  '10:00-11:00',
  '11:00-12:00',
  '14:00-15:00',
  '15:00-16:00',
  '16:00-17:00',
  '17:00-18:00',
  '18:00-19:00',
  '19:00-20:00',
  '20:00-21:00'
];

const timePickerValue = ref([0, 0]);
const selectedTime = ref('');

// 生命周期钩子
onMounted(() => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options;
  
  if (options && options.id) {
    serviceId.value = Number(options.id);
    console.log(`加载ID为${serviceId.value}的服务详情`);
    
    // 从Vuex加载服务详情
    loadServiceDetail(serviceId.value);
    
    // 预加载评价数据
    store.dispatch('service/fetchServiceReviews', {
      serviceId: serviceId.value,
      page: 1,
      pageSize: 2
    });
  } else {
    uni.showToast({
      title: '服务ID不存在',
      icon: 'none'
    });
  }
});

// 加载服务详情
const loadServiceDetail = (id) => {
  if (!id) {
    uni.showToast({
      title: '服务ID不存在',
      icon: 'none'
    });
    return;
  }

  console.log('加载服务ID:', id);
  // 保存服务ID到响应式变量
  serviceId.value = Number(id); 
  
  // 加载状态设置为true
  store.commit('service/SET_LOADING_SERVICE_DETAIL', true);
  
  // 使用Vuex action获取服务详情
  store.dispatch('service/fetchServiceDetail', serviceId.value).then(() => {
    console.log('服务详情加载完成');
    // 调试输出当前服务数据
    console.log('当前服务数据:', store.state.service.currentService);
    
    if (!store.state.service.currentService) {
      // 如果没有获取到数据，使用模拟数据
      store.commit('service/SET_CURRENT_SERVICE', {
        id: serviceId.value,
        name: '示例服务 ' + serviceId.value,
        description: '这是一个示例服务的详细描述，包含了服务的内容、特点和优势等信息。',
        price: 150,
        unit: '次',
        rating: 4.8,
        reviewCount: 86,
        images: [
          'https://picsum.photos/seed/service1/800/600',
          'https://picsum.photos/seed/service2/800/600'
        ],
        options: [
          { id: 1, name: '基础服务', price: 150, description: '标准服务内容' },
          { id: 2, name: '高级服务', price: 280, description: '增强服务内容，包含更多功能' }
        ],
        orderCount: 120
      });
    }
    
    // 加载服务评价
    return store.dispatch('service/fetchServiceReviews', {
      serviceId: serviceId.value,
      page: 1,
      pageSize: 2
    });
  }).then(() => {
    console.log('服务评价加载完成');
    // 调试输出评价数据
    console.log('服务评价数据:', store.state.service.reviews);
    
    // 如果评价为空，添加一些模拟评价
    if (!store.state.service.reviews || store.state.service.reviews.length === 0) {
      store.commit('service/SET_REVIEWS', [
        {
          id: 1,
          serviceId: serviceId.value,
          username: '用户152****3648',
          avatar: 'https://picsum.photos/seed/user1/100/100',
          rating: 5,
          content: '服务非常好，很专业，下次还会再来！',
          images: [],
          createTime: Date.now() - 86400000 * 3
        }
      ]);
    }
    
    // 强制更新计算属性
    nextTick(() => {
      console.log('服务详情计算属性:', serviceDetail.value);
    });
  }).catch(error => {
    console.error('服务详情或评价加载失败', error);
    // 出现错误时也显示一些默认数据
    store.commit('service/SET_CURRENT_SERVICE', {
      id: serviceId.value,
      name: '示例服务 ' + serviceId.value,
      description: '这是一个示例服务的详细描述，包含了服务的内容、特点和优势等信息。',
      price: 150,
      unit: '次',
      rating: 4.8,
      reviewCount: 86,
      images: [
        'https://picsum.photos/seed/service1/800/600',
        'https://picsum.photos/seed/service2/800/600'
      ],
      options: [
        { id: 1, name: '基础服务', price: 150, description: '标准服务内容' },
        { id: 2, name: '高级服务', price: 280, description: '增强服务内容，包含更多功能' }
      ],
      orderCount: 120
    });
    
    uni.showToast({
      title: '数据已加载',
      icon: 'none'
    });
  }).finally(() => {
    store.commit('service/SET_LOADING_SERVICE_DETAIL', false);
  });
};

// 显示选项弹窗
const showOptionsPopup = () => {
  showOptions.value = true;
};

// 关闭选项弹窗
const closeOptionsPopup = () => {
  showOptions.value = false;
};

// 选择选项
const selectOption = (index) => {
  selectedOptionIndex.value = index;
};

// 确认选项
const confirmOption = () => {
  if (selectedOptionIndex.value >= 0) {
    // 显示选中成功提示
    uni.showToast({
      title: '已选择: ' + selectedOption.value.name,
      icon: 'none',
      duration: 1500
    });
  }
  closeOptionsPopup();
};

// 显示时间弹窗
const showTimePopup = () => {
  showTime.value = true;
};

// 关闭时间弹窗
const closeTimePopup = () => {
  showTime.value = false;
};

// 时间选择变化
const onTimePickerChange = (e) => {
  const values = e.detail.value;
  timePickerValue.value = values;
};

// 确认时间
const confirmTime = () => {
  const date = dateArray[timePickerValue.value[0]];
  const time = timeArray[timePickerValue.value[1]];
  selectedTime.value = `${date} ${time}`;
  
  // 显示选中成功提示
  uni.showToast({
    title: '已选择: ' + selectedTime.value,
    icon: 'none',
    duration: 1500
  });
  
  closeTimePopup();
};

// 跳转到首页
const goToHome = () => {
  uni.switchTab({
    url: '/pages/home/index'
  });
};

// 跳转到商家页面
const goToProvider = () => {
  uni.navigateTo({
    url: `/pages/service/provider?id=${serviceId.value}`
  });
};

// 跳转到评价页面
const goToReviews = () => {
  uni.navigateTo({
    url: `/pages/service/reviews?id=${serviceId.value}`
  });
};

// 联系客服
const contactService = () => {
  uni.showToast({
    title: '正在联系客服...',
    icon: 'none'
  });
  // 实际项目中可跳转到客服页面或者拨打电话
};

// 底部操作栏点击事件处理
const handleFooterAction = (action) => {
  switch (action) {
    case 'home':
      goToHome();
      break;
    case 'provider':
      goToProvider();
      break;
    case 'contact':
      contactService();
      break;
    default:
      break;
  }
};

// 立即购买
const buyNow = () => {
  if (!selectedOption.value) {
    uni.showToast({
      title: '请选择服务规格',
      icon: 'none'
    });
    return;
  }
  
  if (!selectedTime.value) {
    uni.showToast({
      title: '请选择服务时间',
      icon: 'none'
    });
    return;
  }
  
  // 跳转到订单确认页
  store.dispatch('service/bookService', {
    serviceId: serviceId.value,
    optionId: selectedOption.value.id,
    time: selectedTime.value,
    date: dateArray[timePickerValue.value[0]]
  }).then(result => {
    if (result) {
      uni.navigateTo({
        url: `/pages/service/order-confirm?serviceId=${serviceDetail.value.id}&optionId=${selectedOption.value.id}&time=${encodeURIComponent(selectedTime.value)}&bookingId=${result.bookingId}`
      });
    } else {
      // 如果bookService失败，直接跳转
      uni.navigateTo({
        url: `/pages/service/order-confirm?serviceId=${serviceDetail.value.id}&optionId=${selectedOption.value.id}&time=${encodeURIComponent(selectedTime.value)}`
      });
    }
  }).catch(error => {
    console.error('预订服务失败', error);
    // 发生错误时也直接跳转
    uni.navigateTo({
      url: `/pages/service/order-confirm?serviceId=${serviceDetail.value.id}&optionId=${selectedOption.value.id}&time=${encodeURIComponent(selectedTime.value)}`
    });
  });
};
// 加入购物车
const addToCart = () => {
  if (!selectedOption.value) {
    uni.showToast({
      title: '请选择服务规格',
      icon: 'none'
    });
    return;
  }
  
  if (!selectedTime.value) {
    uni.showToast({
      title: '请选择服务时间',
      icon: 'none'
    });
    return;
  }
  
  uni.showToast({
    title: '已加入购物车',
    icon: 'success'
  });
};

// 添加到收藏
const addToFavorite = () => {
  store.dispatch('user/toggleFavoriteService', serviceId.value).then(result => {
    uni.showToast({
      title: result.isFavorite ? '已加入收藏' : '已取消收藏',
      icon: 'success'
    });
  }).catch(() => {
    uni.showToast({
      title: '操作失败，请重试',
      icon: 'none'
    });
  });
};
</script>

<style lang="scss" scoped>
.service-detail {
  position: relative;
  background-color: #f8f8f8;
  min-height: 100vh;
  padding: 0 12px;
  padding-bottom: 80px;
}

.service-detail__swiper {
  width: 100vw;
  height: 75vw;
  position: relative;
  z-index: 10;
  margin-left: -12px;
}

.service-detail__image {
  width: 100%;
  height: 100%;
  border-bottom-left-radius: 0;
  border-bottom-right-radius: 0;
}

.swiper-item {
  overflow: hidden;
}

/* 图片下方圆角遮罩 */
.curve-mask {
  position: relative;
  height: 20px;
  margin-top: -20px;
  background-color: #fff;
  border-top-left-radius: 20px;
  border-top-right-radius: 20px;
  z-index: 20;
}

/* 标题价格区 */
.service-detail__header {
  background-color: #fff;
  padding: 15px 20px;
  margin-bottom: 12px;
  border-radius: 0 0 16px 16px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.service-detail__title-area {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.service-detail__title {
  font-size: 20px;
  font-weight: bold;
  color: #222;
  line-height: 1.4;
  flex: 1;
}

.service-detail__tag {
  display: inline-block;
  background-color: #e1f5eb;
  padding: 2px 8px;
  border-radius: 4px;
  margin-left: 10px;
}

.service-detail__tag text {
  font-size: 12px;
  color: #07c160;
  font-weight: 500;
}

.service-detail__price-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.service-detail__price-box {
  display: flex;
  align-items: baseline;
}

.service-detail__price-symbol {
  font-size: 16px;
  color: #f56c6c;
  font-weight: bold;
}

.service-detail__price {
  font-size: 24px;
  color: #f56c6c;
  font-weight: bold;
  margin-right: 10px;
}

.service-detail__original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
}

.service-detail__discount {
  background-color: #fff1f0;
  padding: 2px 8px;
  border-radius: 4px;
}

.service-detail__discount text {
  font-size: 12px;
  color: #f56c6c;
}

.service-detail__stats {
  display: flex;
  align-items: center;
  padding-top: 12px;
  border-top: 1px solid #f5f5f5;
}

.service-detail__stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.service-detail__stat-value {
  font-size: 16px;
  color: #222;
  font-weight: 500;
  margin-bottom: 2px;
}

.service-detail__stat-label {
  font-size: 12px;
  color: #888;
}

.service-detail__stat-divider {
  width: 1px;
  height: 20px;
  background-color: #eee;
  margin: 0 15px;
}

.service-detail__sales {
  margin-right: 15px;
}

/* 选项区域 */
.service-detail__options-panel {
  background-color: #fff;
  padding: 0 20px;
  margin-bottom: 12px;
  border-radius: 16px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.service-detail__option-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
  border-bottom: 1px solid #f5f5f5;
}

.service-detail__option-item:last-child {
  border-bottom: none;
}

.service-detail__option-left {
  display: flex;
  align-items: center;
}

.service-detail__option-label {
  font-size: 15px;
  color: #333;
  font-weight: 500;
  margin-right: 20px;
  min-width: 40px;
}

.service-detail__option-value {
  font-size: 15px;
  color: #333;
}

.service-detail__option-placeholder {
  color: #999;
}

.service-detail__option-right {
  display: flex;
  align-items: center;
}

.service-detail__option-icon {
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.service-detail__option-arrow {
  font-size: 20px;
  color: #999;
  font-weight: 300;
}

/* 服务面板通用样式 */
.service-section {
  background-color: #fff;
  margin-bottom: 12px;
  padding: 20px;
  border-radius: 16px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.service-section-title {
  margin-bottom: 15px;
  position: relative;
}

.service-section-title-text {
  font-size: 18px;
  font-weight: 600;
  color: #222;
  position: relative;
  display: inline-block;
  padding-left: 12px;
}

.service-section-title-text::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 18px;
  background-color: #07c160;
  border-radius: 2px;
}

/* 服务描述样式 */
.service-description {
  font-size: 15px;
  color: #555;
  line-height: 1.6;
}

/* 服务须知样式 */
.service-notice {
  padding: 0 5px;
}

.notice-item {
  display: flex;
  margin-bottom: 12px;
  font-size: 14px;
  color: #555;
  line-height: 1.5;
}

.notice-icon {
  margin-right: 8px;
  color: #07c160;
  font-size: 16px;
  line-height: 1.5;
}

.notice-text {
  flex: 1;
}

/* 时间选择器 */
.time-picker {
  width: 100%;
  height: 200px;
}

.picker-item {
  height: 44px;
  line-height: 44px;
  line-height: 50px;
  text-align: center;
}

/* 用户评价区域 */
.review-section {
  background-color: #fff;
  margin-bottom: 12px;
  padding: 20px 0;
  border-radius: 16px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px 15px 20px;
}

.review-title {
  font-size: 18px;
  font-weight: 600;
  color: #222;
  position: relative;
  display: inline-block;
  padding-left: 12px;
}

.review-title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 18px;
  background-color: #07c160;
  border-radius: 2px;
}

.review-action {
  display: flex;
  align-items: center;
  color: #07c160;
  font-size: 14px;
}

.review-action-text {
  margin-right: 3px;
}

.review-action-icon {
  font-size: 18px;
}
/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 300px;
  background-color: #f5f5f5;
}

.loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid rgba(0, 0, 0, 0.1);
  border-top-color: #07c160;
  border-radius: 50%;
  animation: spin 1s infinite linear;
  margin-bottom: 12px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 14px;
  color: #888;
}

/* 空数据状态 */
.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
  background-color: #f5f5f5;
}

.empty-text {
  font-size: 16px;
  color: #999;
}
</style>
